//
//  ImageDownLoader.m
//  LessonUI17Day
//
//  Created by 左建军 on 15/7/1.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "ImageDownLoader.h"

@implementation ImageDownLoader


#pragma mark - block传值的网络请求 -
- (void)requestImageUrl:(NSString *)imageUrl
           successBlock:(imageDownLoadSuccess)successBlock
             errorBlock:(imageDownLoadError)errorBlock {
    
    self.successBlock = successBlock;
    self.errorBlock = errorBlock;
   
//下载图片之前先检查本地是否已经有图片
    UIImage * image = [self loadLocalImage:imageUrl];
    NSData *imageData = UIImagePNGRepresentation(image);
    //如果图片存在直接跳出；不用下载了
    if (imageData) {
        self.successBlock(imageData);
        return;
    }
    
    NSURL *url = [NSURL URLWithString:[imageUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        if (data) {
            self.successBlock(data);
            
            //下载完成，将图片保存到本地
            [data writeToFile:[self imageFilePath:imageUrl] atomically:YES];
            
        }
        if (connectionError) {
            self.errorBlock(connectionError);
        }
    }];
}

#pragma mark - 代理传值的网络请求 -
- (void)requestImageUrl:(NSString *)imageUrl andDelegate:(id<ImageDownFinishDelegate>)delegate {
    
//    在方法中直接设置代理；
    self.delegate = delegate;
    
    //下载图片之前先检查本地是否已经有图片
    UIImage * image = [self loadLocalImage:imageUrl];
    NSData *imageData = UIImagePNGRepresentation(image);
    //如果图片存在直接跳出；不用下载了
    if (imageData) {
        [_delegate imageDownLoadSuccess:imageData];
        return;
    }
    
    //1、创建url对象; 防止地址中出现中文字符，在创建url的时候首先要进行utf－8转码
    NSURL *url = [NSURL URLWithString:[imageUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    
    //2、创建request对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    //3、发送异步请求；图片信息较大，防止ui出现卡顿现象；
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        //请求成功，调用协议中声明的成功方法
        if (data) {
            [_delegate imageDownLoadSuccess:data];
            
            //下载完成，将图片保存到本地
            [data writeToFile:[self imageFilePath:imageUrl] atomically:YES];
        }
        
        //请求失败，调用协议中声明的失败方法
        if (connectionError) {
            [_delegate imageDownLoadError:connectionError];
        }
    }];
}

#pragma mark - 加载本地图像
- (UIImage *)loadLocalImage:(NSString *)imageUrl
{
    // 获取图像路径
    NSString * filePath = [self imageFilePath:imageUrl];
    UIImage * image = [UIImage imageWithContentsOfFile:filePath];
    
    if (image != nil)
    {
        return image;
    }
    return nil;
}

#pragma mark - 获取图像路径
- (NSString *)imageFilePath:(NSString *)imageUrl
{
    // 获取caches文件夹路径
    NSString * cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    
    // 创建DownloadImages文件夹
    NSString * downloadImagesPath = [cachesPath stringByAppendingPathComponent:@"DownloadImages"];
    NSFileManager * fileManager = [NSFileManager defaultManager];
    
    //判断文件夹是否存在
    if (![fileManager fileExistsAtPath:downloadImagesPath])
    {
        [fileManager createDirectoryAtPath:downloadImagesPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    // 拼接图像文件在沙盒中的路径,因为图像URL有"/",要在存入前替换掉,随意用"_"代替
    NSString * imageName = [imageUrl stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
    NSString * imageFilePath = [downloadImagesPath stringByAppendingPathComponent:imageName];
    
    return imageFilePath;
}



@end
